#include "mainwindow.h"
#include "ui_mainwindow.h"
#include"emoji.h"
#include <QPainter>
void MainWindow::intUI()
{
    //this -> showFullScreen();
    label_text = new QLabel;
    label_text -> setMidLineWidth(150);
    label_text -> setText("字数: 0");
    label_row = new QLabel;
    label_row -> setMidLineWidth(150);
    label_row -> setText("行数: 0");
    ui -> statusBar -> addWidget(label_text);
    ui -> statusBar -> addWidget(label_row);

    spinbox = new QSpinBox;
    spinbox->setValue(30);                                      //字体大小栏初始值为30
    ui -> mainToolBar -> addWidget(new QLabel("字体大小"));
    ui -> mainToolBar -> addWidget(spinbox);                      

    fontcombobox = new QFontComboBox;
    ui -> mainToolBar -> addWidget(new QLabel("字体"));
    ui -> mainToolBar -> addWidget(fontcombobox);
    TextWindow *edit = new TextWindow(this);                    //初始化文件
    edit -> setWindowTitle("未保存文件1");
    edit -> setFontPointSize(30);                               //字体大小初始尺寸30
    ui->mdiArea->addSubWindow(edit);

    searchwindow = new SearchWindow;
    searchwindow -> setWindowTitle("查找和替换");                //设置搜索框名

    time = new QTimer(this);
    time -> start(250);

    ui->mdiArea->setViewMode(QMdiArea::TabbedView);             //设置子窗口显示模式
    page_vised[1] = true;

    Emoji = new emoji();
}

void MainWindow::connect_set()
{
    connect(spinbox,SIGNAL(valueChanged(int)),                  //函数名为on_控件名_信号名字默认是隐式connect，再写connect会产生冲突
            this,SLOT(spinBoxFontSize_valueChanged(int)));

    connect(fontcombobox,SIGNAL(currentIndexChanged(const QString&)),
            this,SLOT(comboFont_currentIndexChanged(const QString&)));

    connect(searchwindow, &SearchWindow::find_signal, this, &MainWindow::compare_and_locate);   //更新

    connect(searchwindow, &SearchWindow::replace_signal, this, &MainWindow::replace);   //替换

    connect(time, &QTimer::timeout, this, &MainWindow::update_count);  //每隔一段时间更新一次count_text

    //connect(&TextWindow::send_close_signal, [&](){
     //   count_page--;
    //})

    connect(Emoji, &emoji::send_signal, this, &MainWindow::insert_emoji);   //插入表情包
}

MainWindow::MainWindow(QWidget *parent) :   //MainWindow类的构造函数
    QMainWindow(parent),
    ui(new Ui::MainWindow)
{
    ui->setupUi(this);
    intUI();
    connect_set();
    /*setCentralWidget(ui->textEdit);*/
    setCentralWidget(ui -> mdiArea);

}

MainWindow::~MainWindow()   //MainWindow类的析构函数
{
    //searchwindow -> close();  //???????????
    delete ui;
}

void MainWindow::on_actioncuti_triggered(bool checked)  //设置文本为粗体
{
    if (warning() == false)
        return;

    QTextCharFormat fff;
    if(checked)
    {
        fff.setFontWeight(QFont::Bold);
    }
    else
    {
        fff.setFontWeight(QFont::Normal);
    }
    activeEdit()->mergeCurrentCharFormat(fff);

}

void MainWindow::spinBoxFontSize_valueChanged(int aFontSize)  //设置文本字体大小
{
    if (warning() == false)
        return;

    QTextCharFormat fff;
    fff.setFontPointSize(aFontSize);
    activeEdit()->mergeCurrentCharFormat(fff);
}

void MainWindow::comboFont_currentIndexChanged(const QString &argl) //设置文本字体
{
    if (warning() == false)
        return;

    QTextCharFormat fff;
    fff.setFontFamily(argl);
    activeEdit()->mergeCurrentCharFormat(fff);
}


void MainWindow::on_actionxieti_triggered(bool checked) //设置文本为斜体
{
    if (warning() == false)
        return;

    QTextCharFormat fff;
    if(checked)
    {
        fff.setFontItalic(QFont::Bold);
    }
    else
    {
        fff.setFontItalic(QFont::StyleNormal);
    }
    activeEdit()->mergeCurrentCharFormat(fff);
}

void MainWindow::on_actionxiahuaxian_triggered(bool checked)    //为文本增添下划线
{
    if (warning() == false)
        return;

    QTextCharFormat fff;
    if(checked)
    {
        fff.setFontUnderline(QFont::Bold);
    }
    else
    {
        fff.setFontUnderline(QFont::StyleNormal);
    }
    activeEdit()->mergeCurrentCharFormat(fff);
}

void MainWindow::on_actionxinjian_triggered()   //新建文件
{
    if (count_page >= 50)
    {
        QMessageBox::warning(this,tr("错误"),tr("当前文件过多"));
        return;
    }

    //MainWindow * newTable = new MainWindow;
    //newTable -> show();
    TextWindow *edit = new TextWindow(this);
    count_page++;
    ui->mdiArea->addSubWindow(edit);
    edit->setFontPointSize(30);
    int num = min_unvised();
    edit->setWindowTitle(tr("未保存文件%1").arg(num));
    edit->show();
}

void MainWindow::on_actiondakai_triggered() //打开文件
{
    if (count_page >= 50)
    {
        QMessageBox::warning(this,tr("错误"),tr("当前文件过多"));
        return;
    }

    QString curpath=QDir::currentPath();//保存当前路径
    QString filter="程序文件(*.h *.cpp);;文本文件(*.txt);;所有文件(*.*)";
    QString filname=QFileDialog::getOpenFileName(this, "打开", curpath, filter);
    if(filname.isEmpty())
    {
        QMessageBox::warning(this,tr("错误"),tr("打开文件失败"));
        return;
    }
    openStreamText(filname);
}

bool MainWindow::openStreamText(const QString &filename) //
{
    QFile file(filename);

    if(!file.exists())//如果文件不存在
        return false;
    if(!file.open(QIODevice::ReadOnly |QIODevice::Text))//如果不是以只读和文本方式打开文件返回false
        return false;


    QTextStream stream(&file);//文本流读取文件
    stream.setCodec("UTF-8");
    stream.setAutoDetectUnicode(true);//自动检测unicode便于显示汉字
    TextWindow *edit = new TextWindow(this);
    count_page++;
    ui -> mdiArea -> addSubWindow(edit);
    edit -> setWindowTitle(filename);
    edit -> file_name = filename;
    edit -> setFontPointSize(30);
    edit -> setPlainText(stream.readAll());

    file.close();
    return true;
}

void MainWindow::on_actionbaocun_triggered()    //保存文件
{
    if (warning() == false)
        return;

    TextWindow* active_page = activeEdit();
    QString file_name;
    if (active_page -> is_saved == false)
        file_name = QFileDialog::getSaveFileName(this,QString("保存路径"),QString("../"),QString("TEXT(*.txt)"));

    QString text= active_page -> toPlainText();
    QFile file(file_name);
    file.open(QIODevice::WriteOnly | QIODevice::Text);
    file.write(text.toUtf8());
    file.close();

    if (file_name.isEmpty() == false)
    {
        active_page -> is_saved = true;
        active_page -> file_name = file_name;
    }
}

void MainWindow::on_actionyanse_2_triggered()   //设置文本颜色
{
    if (warning() == false)
        return;

    QColor color = QColorDialog::getColor(Qt::red,this);
        if(color.isValid())
        {
            QTextCharFormat fmt;
            fmt.setForeground(color);
            activeEdit()->mergeCurrentCharFormat(fmt);
        }
}

void MainWindow::on_actionyouduiqi_triggered()  //设置文本右对齐
{
    if (warning() == false)
        return;

    activeEdit()->setAlignment(Qt::AlignRight);
}


void MainWindow::on_actionzuoduiqi_triggered()  //设置文本左对齐
{
    if (warning() == false)
        return;

    activeEdit()->setAlignment(Qt::AlignLeft);
}

void MainWindow::on_actionjuzhongduiqi_triggered()  //设置文本中间对齐
{
    if (warning() == false)
        return;

    activeEdit()->setAlignment(Qt::AlignCenter);
}

void MainWindow::on_actionsousuohetihuan_triggered()    //打开搜索框
{
    if (warning() == false)
        return;

    searchwindow->show();
}

void MainWindow::update_count()         //更新字数，行数等
{
    if (activeEdit() == nullptr)
        return;

    QString text = activeEdit() -> toPlainText();         //获取文本
    count_row = activeEdit() -> document() ->lineCount(); //获取行数
    int len = text.size();
    int count = 0;
    for (int i = 0; i < len; ++i)
    {
        if (text[i] != ' ' && text[i] != '\n')
        {
            count++;
            if (text[i] >= 0x4E00 && text[i] <= 0x9FA5)     //判断是否为汉字
                continue;
            while (i < len && text[i] != ' ' && text[i] != '\n')
                i++;
        }
    }
    count_text = count;
    label_text -> setText("  字数：" + QString::number(count_text) + "  ");
    label_row -> setText("  行数: " + QString::number(count_row) + "  ");
}

void MainWindow::compare_and_locate(bool option)
{
    if (warning() == false)
        return;

    QString findtext = searchwindow -> getFindText();
    int count_find = activeEdit() -> toPlainText().count(findtext);
    searchwindow -> update_count(count_find);

    if (count_find == 0)
    {
        QMessageBox::information(this, "注意", "未找到查找内容", QMessageBox::Ok);
        return;
    }

    bool ok;
    if (option == 0)    //向前搜索
    {
        ok = activeEdit() -> find(findtext, QTextDocument::FindBackward);
        if (ok == false)
        {
            activeEdit() -> moveCursor(QTextCursor::End);
            activeEdit() -> find(findtext, QTextDocument::FindBackward);
        }
    }
    else                //向后搜索
    {
         ok = activeEdit() -> find(findtext);
         if (ok == false)
         {
             activeEdit() -> moveCursor(QTextCursor::Start);
             activeEdit() -> find(findtext);
         }
    }

    QPalette palette = activeEdit() -> palette();
    palette.setColor(QPalette::Highlight,palette.color(QPalette::Active,QPalette::Highlight));
    activeEdit() -> setPalette(palette);
}

void MainWindow::replace(const QString to_find, const QString to_replace)
{
    if (warning() == false)
        return;

    TextWindow* active_page = activeEdit();
    QTextCursor cursor = active_page -> textCursor();
    if (active_page -> find(to_find) == false)  //判断是否找到
    {
        QMessageBox::information(this, "注意", "未找到查找内容", QMessageBox::Ok);
        return;
    }

    while (active_page -> find(to_find) == true)
    {
        int cursor_position = cursor.position();
        cursor.setPosition(cursor_position, QTextCursor::MoveAnchor);
        cursor.setPosition(cursor_position + to_find.size(), QTextCursor::KeepAnchor);
        cursor.select(QTextCursor::WordUnderCursor);
        cursor.removeSelectedText();
        cursor.insertText(to_replace);
        //cursor.movePosition(QTextCursor::End);
    }
}

void MainWindow::on_actiontupian_triggered()
{
    if (warning() == false)
        return;

    QString fileName = QFileDialog::getOpenFileName(this,
                                    "选择图片",
                                    ".",
                                    "JPEG(*.jpg *.jpeg);;"
                                    "GIF(*.gif);;"
                                    "PNG(*.png)");
       QUrl url(QString("file:%1").arg(fileName));
       QImage image = QImageReader(fileName).read();
       //在文档中添加图片
       activeEdit() -> document() -> addResource(QTextDocument::ImageResource,
                                             url, QVariant(image));
       QTextCursor cursor = activeEdit() -> textCursor();
       QTextImageFormat imgFormat;
       imgFormat.setName(url.toString());      //获取文件路径
       imgFormat.setWidth(image.width());      //设置图片宽
       imgFormat.setHeight(image.height());    //设置图片高
       cursor.insertImage(image);              //在光标处插入图片*/
}

void MainWindow::on_actionbiaoge_triggered()
{
    if (warning() == false)
        return;

    QTextCursor cursor = activeEdit() -> textCursor();
    QTextTableFormat format;    	//表格格式
    format.setCellSpacing(15);
    format.setCellPadding(20);
    cursor.insertTable(3,4,format); //在光标处插入3行4列的表格
}




void MainWindow::on_actionanse_triggered()
{
    qApp->setStyle(QStyleFactory::create("Fusion"));
    qApp->setPalette(QApplication::style()->standardPalette());
    QPalette palette;
    palette.setColor(QPalette::Window, QColor(120,120,120));    //常规背景色
    palette.setColor(QPalette::WindowText, Qt::white);          //一般前景色
    palette.setColor(QPalette::Base, QColor(53,53,53));         //文本输入窗体部件(比方QTextEdit,QLinedit,QPlainTextEdit等)的背景色
    palette.setColor(QPalette::AlternateBase, QColor(53,53,53));//用作具有交替行颜色的视图中的备用背景色
    palette.setColor(QPalette::ToolTipBase, Qt::white);         //用作 QToolTip 和 QWhatsThis 的背景色
    palette.setColor(QPalette::ToolTipText, Qt::white);         //用作 QToolTip 和 QWhatsThis 的前景色
    palette.setColor(QPalette::Text, Qt::white);                //
    palette.setColor(QPalette::Button, QColor(53,53,53));       //常规按钮背景色
    palette.setColor(QPalette::ButtonText, Qt::white);          //指button窗体部件
    palette.setColor(QPalette::BrightText, Qt::red);            //
    palette.setColor(QPalette::Highlight, QColor(142,45,197).lighter());//高亮
    palette.setColor(QPalette::HighlightedText, Qt::black);     //

    qApp->setPalette(palette);
}

void MainWindow::on_actionqingxin_triggered()
{
    if (warning() == false)
        return;
    qApp->setStyle(QStyleFactory::create("Fusion"));
    qApp->setPalette(QApplication::style()->standardPalette());
    QPalette palette;
    palette.setColor(QPalette::Window, QColor(255,255,240));
    palette.setColor(QPalette::WindowText, Qt::black);
    palette.setColor(QPalette::Base, QColor(193,255,193));
    palette.setColor(QPalette::AlternateBase, QColor(53,53,53));
    palette.setColor(QPalette::ToolTipBase, Qt::black);
    palette.setColor(QPalette::ToolTipText, Qt::black);
    palette.setColor(QPalette::Text, Qt::black);
    palette.setColor(QPalette::Button, QColor(53,53,53));
    palette.setColor(QPalette::ButtonText, Qt::gray);
    palette.setColor(QPalette::BrightText, Qt::yellow);
    palette.setColor(QPalette::Highlight, QColor(0,255,255).lighter());
    palette.setColor(QPalette::HighlightedText, Qt::black);

    qApp->setPalette(palette);
}

void MainWindow::on_actionduocai_triggered()
{
    qApp->setStyle(QStyleFactory::create("Fusion"));
    qApp->setPalette(QApplication::style()->standardPalette());
    QPalette palette;
    palette.setColor(QPalette::Window, QColor(120,120,120));
    palette.setColor(QPalette::WindowText, Qt::white);
    palette.setColor(QPalette::Base, QColor(53,53,53));
    palette.setColor(QPalette::AlternateBase, QColor(53,53,53));
    palette.setColor(QPalette::ToolTipBase, Qt::white);
    palette.setColor(QPalette::ToolTipText, Qt::white);
    palette.setColor(QPalette::Text, Qt::white);
    palette.setColor(QPalette::Button, QColor(53,53,53));
    palette.setColor(QPalette::ButtonText, Qt::white);
    palette.setColor(QPalette::BrightText, Qt::red);
    palette.setColor(QPalette::Highlight, QColor(142,45,197).lighter());
    palette.setColor(QPalette::HighlightedText, Qt::black);

    qApp->setPalette(palette);
}

TextWindow *MainWindow::activeEdit()		//返回当前活动窗口指针
{
    if(QMdiSubWindow * window = ui->mdiArea->activeSubWindow()){
        return qobject_cast<TextWindow *>(window->widget());
    }
    return nullptr;
}

void MainWindow::on_actionjianqie_triggered()
{
    if (warning() == false)
        return;

    activeEdit()->cut();
}

void MainWindow::on_actionfuzhi_triggered()
{
    if (warning() == false)
        return;

    activeEdit()->copy();
}

void MainWindow::on_actionzhantie_triggered()
{
    if (warning() == false)
        return;

    activeEdit()->paste();
}

void MainWindow::on_actioncode_triggered()
{
    CodeEditor *editor=new CodeEditor();
    editor->resize(500,300);
    editor->setFont(QFont("YouYuan",15,QFont::Bold,true));

    QMdiSubWindow * window = ui->mdiArea->activeSubWindow();  //
    QString text = activeEdit() -> toPlainText();
    window->close();
    ui->mdiArea->addSubWindow(editor);
    editor->insertPlainText(text);

    editor->show();
}

int MainWindow::min_unvised()
{
    int min_index = 0;
    for (int i = 1; i <= max_page; ++i)
        if (page_vised[i] != true)
        {
            page_vised[i] = true;
            min_index = i;
            break;
        }
    return min_index;
}

bool MainWindow::warning()
{
    if (activeEdit() == nullptr)
    {
        QMessageBox::information(this, "注意", "当前未新建或打开文本", QMessageBox::Ok);
        return false;
    }
    return true;
}
void MainWindow::on_actionbiaoqing_triggered()
{
    Emoji -> show();
    /*QTextBrowser *emoji=new QTextBrowser;
    emoji->setWindowTitle(tr("表情"));
    emoji->resize(500,300);
    emoji->setFontPointSize(15);
    emoji->show();
    char32_t  t[] = {0x1F601,0x0};
        for(char32_t i = 0x1F601 ; i <=  0x1F64F ; ++i)
        {
           t[0] = i ;
           emoji->insertPlainText(QString::fromUcs4(t));
        }*/
}
void MainWindow::insert_emoji(QString path)
{
    if (warning() == false)
        return;

    TextWindow* active_page = activeEdit();
    QString fileName = path;
    QUrl url(QString("file:%1").arg(fileName));
    QImage image = QImageReader(fileName).read();
    //在文档中添加图片
    //activeEdit() -> document() -> addResource(QTextDocument::ImageResource,
      //                                    url, QVariant(image));
    active_page -> document() -> addResource(QTextDocument::ImageResource, url, QVariant(image));
    QTextCursor cursor = activeEdit() -> textCursor();
    QTextImageFormat imgFormat;
    imgFormat.setName(url.toString());      //获取文件路径
    cursor.insertImage(image);              //在光标处插入图片/**/
}

